/**
 * Created by YJH on 2018/6/4.
 */
import {
    AsyncStorage
}from 'react-native';
import DataRespository, {FLAG_STORAGE} from './DataRespository';


export default class RepositoryAboutUtil {
    constructor(aboutCommon) {
        this.aboutCommon = aboutCommon;
        this.dataRespository = new DataRespository(FLAG_STORAGE.flag_my);
        this.itemMap=new Map();
    }

    /** 检测时间有没有过时的方法
     * 过时返回false
     * */
    _checkData(longTime) {
        // return false;
        let cDate = new Date();//当前
        let tDate = new Date();//目标


        tDate.setTime(longTime);
        if (cDate.getMonth() !== tDate.getMonth())return false;
        if (cDate.getDay() !== tDate.getDay())return false;
        if (cDate.getHours() - tDate.getHours() > 4)return false;

        return true;
    }

    /**
     * 功能：通知数组发生改变
     * @param key
     * @param value
     */
    updateData(key, value) {
        this.itemMap.set(key, value);
        var arr=[];
        for(var value of this.itemMap.values()){
            arr.push(value);
        }
        this.aboutCommon.onNotifyDataChanged(arr);
    }

    /**
     * 功能：根据指定的url获取数据
     * @param url
     */
    _fetchRepository(url) {
        this.dataRespository.fetchRespository(url)
            .then(result => {
                if (result) {
                    this.updateData(url, result);
                    if (!this._checkData(result.update_date)) {
                        return this.dataRespository.fetNetRespository(url);
                    }
                }
            })
            .then(result => {
                if (result) {
                    this.updateData(url, result);
                }
            })
            .catch(e => {
            });
    }

    /**
     * 功能：根据批量的url获取批量数据
     * @param urls
     */
    fetchRepositorys(urls) {
        for(let i=0,l=urls.length;i<l;i++){
            var url=urls[i];
            this._fetchRepository(url);
        }
    }
}